const puppeteer = require('puppeteer');
// const schedule = require('node-schedule')
const Log = require('./log')
const logger = new Log()

const cmdArgs = require('./getEnv')

function waitForlogin(page, _config) {
    return new Promise(resolve => {
        page.on('load', async function () {
            const html= await page.content()
            logger.info(html)
            return
            Promise.all([
                page.$eval('.input-user', (el, _config) => {
                    el.value = _config.user
                    el.dispatchEvent(new Event('input'))
                }, _config),
                page.$eval('.input-pwd', (el, _config) => {
                    el.value = _config.pwd
                    el.dispatchEvent(new Event('input'))
                }, _config)
            ]).then(() => {
                page.click('.login-btn')
                page.waitForNavigation({
                    timeout: 30 * 1000,
                    waitUntil: ['networkidle0']
                }).then(resolve)
            })
        })
    })
}

async function _waitForFillItem(page) {
    logger.info('填报网址：', page.url())
    const listen = page.waitForNavigation({
        waitUntil: ['networkidle0']
    })
    await page.waitForResponse('https://sgpt.zjwater.com/oapi/water-manage-virus/api/fillin/listUserSituationByUser');
    await page.evaluate(() => {
        return new Promise(resolve => {
            const btn=document.querySelector('.m-b-20.van-button.van-button--primary.van-button--large')
            // let dom = document.querySelector('.van-col > .van-button')
            // if (!dom) {
            //     dom = document.querySelector('.footer > .van-button')
            // }
            btn.click()
            setTimeout(() => {
                document.querySelector('.van-dialog .van-dialog__confirm').click()
                resolve()
            }, 20)
        })
    })
    await listen
    // await page.waitForResponse('https://sgpt.zjwater.com/oapi/water-manage-virus/api/fillin/getMyReportStatus');
}

async function waitForFillItem(page, idx) {
    const listen = page.waitForNavigation({
        waitUntil: ['networkidle0']
    })
    // page.on('request',function(interceptedRequest){
    //     console.log('request:',interceptedRequest.url())
    // })
    await page.evaluate((idx) => {
        document.querySelectorAll('.content-1 .item-1')[idx].click()
    }, idx)
    logger.info('click item' + idx)
    await listen.then(() => _waitForFillItem(page))
    // await new Promise(()=>{})
}

async function execWithcapturer(fn, ...args) {
    try {
        await fn(...args)
    } catch (e) {
        logger.error(e.message)
        // return new Promise(() => { })
        throw e
    }
}

const autoStart = async (config) => {
    logger.info('--------------------------------------------------------')
    logger.info(`user:${config.user},开始执行填报`)
    const launchOption = {
        headless: !cmdArgs.dev,
        devtools: cmdArgs.dev,
        // args: ['--no-sandbox']
    }
    // if (!cmdArgs.dev) {
    //     // launchOption.executablePath = '/usr/bin/chromium-browser'
    //     launchOption.executablePath = 'node_modules/puppeteer/.local-chromium/linux-818858/chrome-linux/chrome'
    // }
    const browser = await puppeteer.launch(launchOption);
     const [page]= await browser.pages()
    // const page = await browser.newPage();
    page.setDefaultNavigationTimeout(10 * 1000)
    page.goto('http://sgpt.zjwater.com/VirusReport/#/login');
    await execWithcapturer(waitForlogin, page, config)
    logger.info('登录成功')
    await execWithcapturer(waitForFillItem, page, 0)
    logger.info('完成第一项填报')
    // await execWithcapturer(waitForFillItem, page, 1)
    // logger.info('完成第二项填报')
    // await execWithcapturer(waitForFillItem, page, 2)
    // logger.info('完成第三项填报')
    await page.close()
    logger.info('填报完成')
    //   await page.evaluate()
    // other actions...
    await browser.close();
}

module.exports=autoStart

